﻿using System.Text;
using KSSModel;
using KSSOnline.Controller;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using Utilities;
using System.Web.Configuration;
using OfficeOpenXml;

namespace KSSApi
{
    /// <summary>
    /// Summary description for Api
    /// </summary>
    public class Api : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest post = context.Request;
            string ADAuthen = context.User.Identity.Name;
            string ip = HttpContext.Current.Request.UserHostAddress;
            string Medthod = post["metdhodName"];
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string value;
            string uploadFolder;
            //context.Response.ContentType = "text/plain";
            if (!String.IsNullOrEmpty(Medthod))
            {
                switch (Medthod.Trim())
                {
                    case "SaveForm":
                        value = post["postData"];
                        tblDoc doc = new tblDoc();// (tblDoc)serializer.Deserialize(value, typeof(tblDoc));
                        //var ValueList =  (Dictionary<string, object>)serializer.DeserializeObject(value);
                        var ValueList = JsonConvert.DeserializeObject<List<docPropertyData>>(value);// (List<docPropertyData>)serializer.Deserialize(value);

                        for (int i = ValueList.Count - 1; i >= 0; i--)
                        {
                            switch (ValueList[i].propertyName)
                            {
                                case "id":
                                    doc.id = ValueList[i].dataNvarchar;
                                    ValueList.RemoveAt(i);
                                    break;
                                case "title":
                                    doc.title = ValueList[i].dataNvarchar;
                                    ValueList.RemoveAt(i);
                                    break;

                                case "createdBy":
                                    doc.createdBy = ValueList[i].dataNvarchar;
                                    ValueList.RemoveAt(i);
                                    break;
                                case "createdDate":
                                    doc.createdDate = ValueList[i].dataDate ?? DateTime.Now;
                                    ValueList.RemoveAt(i);
                                    break;
                                case "approved1Date":
                                    doc.approved1Date = ValueList[i].dataDate ?? DateTime.Now;
                                    ValueList.RemoveAt(i);
                                    break;
                                case "approved2Date":
                                    doc.approved2Date = ValueList[i].dataDate ?? DateTime.Now;
                                    ValueList.RemoveAt(i);
                                    break;
                                case "approvedQMDate":
                                    doc.approvedQMDate = ValueList[i].dataDate ?? DateTime.Now;
                                    ValueList.RemoveAt(i);
                                    break;
                                case "departmentName":
                                    doc.departmentName = ValueList[i].dataNvarchar;
                                    ValueList.RemoveAt(i);
                                    break;
                                case "createdByName":
                                    doc.createdByName = ValueList[i].dataNvarchar;
                                    ValueList.RemoveAt(i);
                                    break;
                                case "approver1":
                                    doc.approver1 = ValueList[i].dataNvarchar;
                                    ValueList.RemoveAt(i);
                                    break;
                                case "approver2":
                                    doc.approver2 = ValueList[i].dataNvarchar;
                                    ValueList.RemoveAt(i);
                                    break;
                                case "status":
                                    doc.status = ValueList[i].dataInt ?? 0;
                                    if (doc.status == 30)
                                    {
                                        doc.tqm = HttpContext.Current.User.Identity.Name;
                                    }
                                    ValueList.RemoveAt(i);
                                    break;
                                case "score":
                                    doc.score = ValueList[i].dataInt ?? 0;
                                    ValueList.RemoveAt(i);
                                    break;
                                case "cash":
                                    doc.cash = ValueList[i].dataDecimal ?? 0;
                                    ValueList.RemoveAt(i);
                                    break;
                                case "docTag":
                                    var DocTags = JsonConvert.DeserializeObject<List<tblDocTag>>(ValueList[i].dataNvarchar);
                                    if (DocTags.Count > 0)
                                    {
                                        Result addTag = kssForm.AddDocTag(DocTags);
                                        if (!addTag.success)
                                        {
                                            context.Response.Write(serializer.Serialize(addTag));
                                            context.Response.End();
                                        }
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                        string emailApprover1 = string.Empty;
                        string emailApprover2 = string.Empty;
                        string sendMailError;
                        if (doc.id == null)
                        {
                            doc.id = KSSMaster.createDocumentID();
                            ValueList.ForEach(item => item.docId = doc.id);
                            context.Response.Write(kssForm.AddDoc(doc, ValueList));
                            emailApprover1 = UserHelper.GetUserbyUserName(doc.approver1).Email;
                            emailApprover2 = UserHelper.GetUserbyUserName(doc.approver2).Email;
                            sendEmail(doc);
                            context.Response.End();
                        }
                        else
                        {
                            ValueList.ForEach(item => item.docId = doc.id);
                            context.Response.Write(kssForm.EditDoc(doc, ValueList));
                            sendEmail(doc);
                            context.Response.End();
                        }

                        break;
                    case "getlastDoc":
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(JsonConvert.SerializeObject(UserHelper.GetLastSelectedApprover(HttpContext.Current.User.Identity.Name)));
                        context.Response.End();

                        break;
                    case "gettagscate":
                        context.Response.ContentType = "text/plain";
                        if (string.IsNullOrEmpty(post["sort"]))
                        {
                            context.Response.Write(TagHelper.GetAllTagCate());
                            context.Response.End();
                        }
                        else
                        {
                            string order = post["order"] ?? "asc";
                            context.Response.Write(TagHelper.GetAllTagCate(post["sort"] + " " + order));
                            context.Response.End();
                        }
                        break;
                    case "gettags":
                        context.Response.ContentType = "text/plain";
                        if (string.IsNullOrEmpty(post["sort"]))
                        {
                            context.Response.Write(TagHelper.GetTag());
                            context.Response.End();
                        }
                        else
                        {
                            string order = post["order"] ?? "asc";
                            context.Response.Write(TagHelper.GetTag(post["sort"] + " " + order));
                            context.Response.End();
                        }
                        break;
                    case "getalluser":
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(UserHelper.GetAllUser());
                        context.Response.End();
                        break;
                    case "getalluserrole":
                        context.Response.ContentType = "text/plain";
                        string searchKeyworkd = post["keyword"];
                        string searchType = post["searchType"];
                        context.Response.Write(UserHelper.getUserwithRole(searchKeyworkd, searchType));
                        context.Response.End();
                        break;

                    case "getallrole":
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(UserHelper.getAllRole());
                        context.Response.End();
                        break;

                    case "getallempID":
                        var empallid = from emp in UserHelper.getAllEMP()
                                       select new
                                                  {
                                                      mempid = emp.mstaffno.Substring(6, 4),

                                                  };
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(JsonConvert.SerializeObject(empallid));
                        context.Response.End();
                        break;
                    case "getcashbyuser":

                        string usernameCash = post["username"];
                        if (usernameCash == null)
                        {
                            context.Response.End();
                        }
                        var userCashs = CashHelper.GetCashByUser(usernameCash);
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(serializer.Serialize(userCashs));
                        context.Response.End();
                        break;
                    case "getemp":
                        string empid = post["empid"];
                        if (empid == null)
                        {
                            context.Response.End();
                        }
                        var Emp = UserHelper.getEMP(empid);
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(JsonConvert.SerializeObject(Emp));
                        context.Response.End();
                        break;
                    case "verifyemp":
                        string empidVerify = post["empid"];
                        if (empidVerify == null)
                        {
                            context.Response.End();
                        }
                        var EmpVerify = UserHelper.getEMP(empidVerify);
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(JsonConvert.SerializeObject(EmpVerify.Select(d => d.mstaffno)));
                        context.Response.End();
                        break;
                    case "getusercash":
                        context.Response.ContentType = "text/plain";
                        if (!string.IsNullOrEmpty(post["exportCSV"]) && post["exportCSV"] == "true")
                        {

                            var ds2 = CashHelper.GetUserCashCsv();
                            using (ExcelPackage pck = new ExcelPackage())
                            {
                                //Create the worksheet
                                ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Data");
                                ws.Cells["A1"].LoadFromCollection(ds2, true);
                                context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                                context.Response.AddHeader("content-disposition", "attachment;  filename=dataExport.xlsx");
                                context.Response.BinaryWrite(pck.GetAsByteArray());
                                context.Response.End();
                            }

                            break;
                        }
                        else if (string.IsNullOrEmpty(post["sort"]))
                        {
                            context.Response.Write(CashHelper.GetUserCash());
                            context.Response.End();
                        }
                        else
                        {
                            string order = post["order"] ?? "asc";
                            context.Response.Write(TagHelper.GetTag(post["sort"] + " " + order));
                            context.Response.End();
                        }

                        break;
                    case "PayCashs":
                        value = post["postData"];

                        var payCashs = JsonConvert.DeserializeObject<List<tblPayCash>>(value);
                        int paygroup = CashHelper.AddCashGroup(new tblPayGroup { description = "Pay to employee", payDate = DateTime.Now });
                        payCashs.ForEach(item => item.PaygroupID = paygroup);
                        payCashs.ForEach(item => item.PayDate = DateTime.Now);

                        if (CashHelper.AddCash(payCashs))
                        {
                            context.Response.Write(serializer.Serialize(new Result(true)));
                        }
                        else
                        {
                            context.Response.Write(serializer.Serialize(new Result(false)));
                        }
                        context.Response.End();
                        break;

                    case "addTagCate":
                        var cateName = post["tagCateName"];
                        var cateIsDisable = post["isDisable"];
                        var tagCate = new tblTagCate()
                        {
                            tagCateName = cateName,
                            isDisable = !string.IsNullOrEmpty(
                                cateIsDisable),
                            createBy = post.LogonUserIdentity.Name ?? "admin",
                            created = DateTime.Now
                        };
                        context.Response.Write(TagHelper.AddTagCate(tagCate));
                        context.Response.End();
                        break;

                    case "addUser":
                        var usernameNew = post["empId"];
                        var nameNew = post["name"];
                        var pass = post["password"];
                        var getUser = UserHelper.getEMP(usernameNew);
                        if (getUser != null && getUser.Count > 0 && getUser.Any(u => u.mnameTh.Contains(nameNew.Trim())))
                        {
                            var newUser = new tblUser()
                            {
                                UserName = usernameNew,
                                Password = pass,
                                FirstName = getUser[0].mnameTh,
                                Lastname = getUser[0].surnameTh,
                                CreateDate = DateTime.Now
                            };
                            var resultAdd = UserHelper.addUser(newUser);
                            // no need approver1 AND approver2 any more
                            //var roleUser = "user";
                            //if (getUser[0].mpositionTh.Contains("หัวหน้างาน"))
                            //{
                            //    roleUser = "approver1";
                            //}
                            //if (getUser[0].mapplevel.Equals("sm", StringComparison.OrdinalIgnoreCase))
                            //{
                            //    roleUser = "approver2";
                            //}

                            //var newUserRole = new tblUserRole { UserName = usernameNew, RoleName = roleUser };
                            //UserHelper.addUserRole(newUserRole);

                            context.Response.Write(resultAdd);
                        }
                        context.Response.End();
                        break;
                    case "addTag":
                        var tagName = post["tagName"];
                        var tagCateParent = post["cateId"];
                        var tagIsDisable = post["isDisable"];

                        var tag = new tblTag()
                        {
                            tagName = tagName,
                            tagCateId = Convert.ToInt32(tagCateParent),
                            isDisable = !string.IsNullOrEmpty(
                            tagIsDisable),
                            createBy = post.LogonUserIdentity.Name ?? "admin",
                            created = DateTime.Now
                        };
                        context.Response.Write(TagHelper.AddTag(tag));
                        context.Response.End();
                        break;
                    case "removeTagCate":
                        var cateID = post["id"];
                        if (!string.IsNullOrEmpty(cateID))
                        {
                            int id = -1;
                            int.TryParse(cateID, out id);
                            if (id != -1)
                            {
                                context.Response.Write(TagHelper.DeleteTagCate(id));
                                context.Response.End();
                            }
                        }
                        context.Response.Write(serializer.Serialize(new Result(false, "Please check cate id")));
                        context.Response.End();
                        break;
                    case "removeTag":
                        var tagID = post["id"];
                        if (!string.IsNullOrEmpty(tagID))
                        {
                            int id = -1;
                            int.TryParse(tagID, out id);
                            if (id != -1)
                            {
                                context.Response.Write(TagHelper.DeleteTag(id));
                                context.Response.End();
                            }
                        }
                        context.Response.Write(serializer.Serialize(new Result(false, "Please check cate id")));
                        context.Response.End();
                        break;

                    case "editUserRole":
                        var usernameRole = post["usernameRole"];
                        var oldRole = post["oldRole"];
                        var newRole = post["newRole"];
                        var oldRole2 = new tblUserRole { RoleName = oldRole, UserName = usernameRole };
                        var newRole2 = new tblUserRole { RoleName = newRole, UserName = usernameRole };

                        context.Response.Write(UserHelper.updateUserRole(oldRole2, newRole2));
                        context.Response.End();
                        break;
                    case "editTagCate":
                        var cateIdEdit = post["id"];
                        var cateNameEdit = post["tagCateName"];
                        var cateIsDisableEdit = post["isDisable"];
                        int cateid = -1;
                        int.TryParse(cateIdEdit, out cateid);
                        if (cateid == -1)
                        {
                            context.Response.Write(serializer.Serialize(new Result(false, "Please check cate id")));
                        }
                        var tagCateEdit = new tblTagCate()
                        {
                            tagCateId = cateid,
                            tagCateName = cateNameEdit,
                            isDisable = !string.IsNullOrEmpty(
                                cateIsDisableEdit),
                            createBy = post.LogonUserIdentity.Name ?? "admin"
                        };

                        context.Response.Write(TagHelper.EditTagCate(tagCateEdit));
                        context.Response.End();
                        break;
                    case "editTag":
                        var tagIdEdit = post["id"];
                        var tagNameEdit = post["tagName"];
                        var tagParent = post["cateId"];
                        var tagIsDisableEdit = post["isDisable"];
                        int tagid = -1;
                        int.TryParse(tagIdEdit, out tagid);
                        if (tagid == -1)
                        {
                            context.Response.Write(serializer.Serialize(new Result(false, "Please check cate id")));
                        }
                        var tagEdit = new tblTag()
                        {
                            tagId = tagid,
                            tagName = tagNameEdit,
                            tagCateId = Convert.ToInt32(tagParent),
                            isDisable = !string.IsNullOrEmpty(
                            tagIsDisableEdit),
                            createBy = post.LogonUserIdentity.Name ?? "admin"
                        };
                        context.Response.Write(TagHelper.EditTag(tagEdit));
                        context.Response.End();
                        break;
                    case "getta1cate":
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(A1ItemHelper.GetAllA1Cate());
                        context.Response.End();
                        break;
                    case "getta1catewithSection3":
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(A1ItemHelper.GetAllA1CateWithSection(3));
                        context.Response.End();
                        break;
                    case "GetBarChart2":
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(ChartHelper.GetBarChart2(3));
                        context.Response.End();
                        break;


                    case "gettgrp1":
                        context.Response.ContentType = "text/plain";
                        var columnId = post["cid"];
                        var rowId = post["rid"];

                        context.Response.Write(ChartHelper.GetG1(Convert.ToInt32(columnId), Convert.ToInt32(rowId)));
                        context.Response.End();
                        break;
                    case "addta1cate":
                        var a1CateName = post["a1CateName"];
                        var a1CateLocation = post["locationId"];
                        var a1CateIsDisable = post["isDisable"];
                        var a1Cateadd = new tblA1Cate()
                        {
                            a1CateName = a1CateName,
                            isDisable = !string.IsNullOrEmpty(
                                a1CateIsDisable),
                            createBy = post.LogonUserIdentity.Name ?? "admin",
                            created = DateTime.Now
                        };
                        var a1CateLocationadd = new tblA1CateLocation() { locationId = a1CateLocation };

                        context.Response.Write(A1ItemHelper.AddA1Cate(a1Cateadd, a1CateLocationadd));
                        context.Response.End();
                        break;
                    case "editta1cate":
                        var a1CateIdEdit = post["id"];
                        var a1CateLocationEdit = post["locationId"];
                        var a1CateNameEdit = post["a1CateName"];
                        var a1CateIsDisableEdit = post["isDisable"];
                        int a1Cateid = -1;
                        int.TryParse(a1CateIdEdit, out a1Cateid);
                        if (a1Cateid == -1)
                        {
                            context.Response.Write(serializer.Serialize(new Result(false, "Please check a1Cateid id")));
                        }
                        var a1CateEdit = new tblA1Cate()
                        {
                            a1CateId = a1Cateid,
                            a1CateName = a1CateNameEdit,
                            isDisable = !string.IsNullOrEmpty(
                                a1CateIsDisableEdit),
                            //createBy = post.LogonUserIdentity.Name ?? "admin"
                        };
                        var a1CateLocationedit = new tblA1CateLocation() { a1CateId = a1Cateid, locationId = a1CateLocationEdit };
                        context.Response.Write(A1ItemHelper.EditA1Cate(a1CateEdit, a1CateLocationedit));
                        context.Response.End();
                        break;
                    case "removeta1cate":
                        var a1CateIdremove = post["id"];
                        if (!string.IsNullOrEmpty(a1CateIdremove))
                        {
                            int id = -1;
                            int.TryParse(a1CateIdremove, out id);
                            if (id != -1)
                            {
                                context.Response.Write(A1ItemHelper.DeleteA1Cate(id));
                                context.Response.End();
                            }
                        }
                        context.Response.Write(serializer.Serialize(new Result(false, "Please check a1CateId")));
                        context.Response.End();
                        break;
                    case "getta1item":
                        context.Response.ContentType = "text/plain";
                        var a1ItemcateId = post["cateId"];
                        int cateId = -1;
                        if (!string.IsNullOrEmpty(a1ItemcateId))
                        {
                            int.TryParse(a1ItemcateId, out cateId);
                        }
                        context.Response.Write(cateId == -1
                                                   ? A1ItemHelper.GetAllA1Item()
                                                   : A1ItemHelper.GetAllA1Item(cateId));
                        context.Response.End();
                        break;
                    case "addta1item":
                        var a1ItemName = post["a1ItemName"];
                        var a1ItemParent = post["cateId"];
                        var a1ItemIsDisable = post["isDisable"];
                        var a1ItemLocation = post["locationId"];
                        var a1Itemadd = new tblA1Item()
                        {
                            a1ItemName = a1ItemName,
                            a1CateId = Convert.ToInt32(a1ItemParent),
                            isDisable = !string.IsNullOrEmpty(
                                a1ItemIsDisable),
                            createBy = post.LogonUserIdentity.Name ?? "admin",
                            created = DateTime.Now
                        };
                        var a1ItemLocationadd = new tblA1ItemLocation() { locationId = a1ItemLocation };
                        context.Response.Write(A1ItemHelper.AddA1Item(a1Itemadd, a1ItemLocationadd));
                        context.Response.End();
                        break;
                    case "edita1item":
                        var a1ItemIdEdit = post["id"];
                        var a1ItemNameEdit = post["a1ItemName"];
                        var a1ItemParentEdit = post["cateId"];
                        var a1ItemIsDisableEdit = post["isDisable"];
                        var a1ItemLocationEdit = post["locationId"];
                        int a1Itemid = -1;
                        int.TryParse(a1ItemIdEdit, out a1Itemid);
                        if (a1Itemid == -1)
                        {
                            context.Response.Write(serializer.Serialize(new Result(false, "Please check cate id")));
                        }
                        var a1ItemEdit = new tblA1Item()
                        {
                            a1ItemId = a1Itemid,
                            a1ItemName = a1ItemNameEdit,
                            a1CateId = Convert.ToInt32(a1ItemParentEdit),
                            isDisable = !string.IsNullOrEmpty(
                            a1ItemIsDisableEdit),
                            //createBy = post.LogonUserIdentity.Name ?? "admin"
                        };
                        var a1ItemLocationedit = new tblA1ItemLocation() { a1ItemId = a1Itemid, locationId = a1ItemLocationEdit };
                        context.Response.Write(A1ItemHelper.EditA1Item(a1ItemEdit, a1ItemLocationedit));
                        context.Response.End();
                        break;
                    case "removeta1item":
                        var a1ItemIdremove = post["id"];
                        if (!string.IsNullOrEmpty(a1ItemIdremove))
                        {
                            int id = -1;
                            int.TryParse(a1ItemIdremove, out id);
                            if (id != -1)
                            {
                                context.Response.Write(A1ItemHelper.DeleteA1Item(id));
                                context.Response.End();
                            }
                        }
                        context.Response.Write(serializer.Serialize(new Result(false, "Please check a1ItemIdremove")));
                        context.Response.End();
                        break;
                    case "getdocbyID":
                        context.Response.ContentType = "text/plain";
                        var docid = post["DocID"];
                        context.Response.Write(kssForm.GetDocByID("doc1"));
                        context.Response.End();
                        break;
                    case "getdocPropbyID":
                        context.Response.ContentType = "text/plain";
                        var propdocid = post["id"];
                        context.Response.Write(kssForm.GetDocPropByDocID(propdocid));
                        context.Response.End();
                        break;
                    case "getdocbyUsername":

                        var username = post["UserName"];
                        var status = post["Status"];
                        var tags = post["Tag"];
                        var exportCSV = post["iscsv"];
                        if (!string.IsNullOrEmpty(exportCSV) && exportCSV == "true")
                        {

                            context.Response.AddHeader("Content-Disposition", "attachment;filename=dataExport.csv");

                            List<TblKDoc> ds2 = new List<TblKDoc>();
                            context.Response.ContentEncoding = Encoding.UTF32;
                            if (!string.IsNullOrEmpty(tags))
                            {
                                if (tags.ToLower() == "tagall")
                                {
                                    tags = null;
                                }
                            }
                            if (status != null && tags != null)
                            {
                                ds2 = kssForm.GetDocByUsername(username, Convert.ToInt32(status), tags);
                            }
                            else if (tags != null && status == null)
                            {
                                ds2 = kssForm.GetDocByUsername(username, tags);
                            }
                            else if (status != null)
                            {
                                ds2 = kssForm.GetDocByUsername(username, Convert.ToInt32(status));
                            }
                            else
                            {
                                ds2 = kssForm.GetDocByUsername(username);
                            }

                            using (ExcelPackage pck = new ExcelPackage())
                            {
                                //Create the worksheet
                                ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Data");
                                ws.Cells["A1"].LoadFromCollection(ds2, true);
                                context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                                context.Response.AddHeader("content-disposition", "attachment;  filename=dataExport.xlsx");
                                context.Response.BinaryWrite(pck.GetAsByteArray());
                                context.Response.End();
                            }

                            break;
                        }
                        else
                        {
                            context.Response.ContentType = "text/plain";
                            if (!string.IsNullOrEmpty(tags))
                            {
                                if (tags.ToLower() == "tagall")
                                {
                                    tags = null;
                                }
                            }
                            if (status != null && tags != null)
                            {
                                context.Response.Write(serializer.Serialize(kssForm.GetDocByUsername(username, Convert.ToInt32(status), tags)));
                                context.Response.End();
                            }
                            else if (tags != null && status == null)
                            {
                                context.Response.Write(serializer.Serialize(kssForm.GetDocByUsername(username, tags)));
                                context.Response.End();
                            }
                            else if (status != null)
                            {
                                context.Response.Write(serializer.Serialize(kssForm.GetDocByUsername(username, Convert.ToInt32(status))));
                                context.Response.End();
                            }
                            else
                            {
                                context.Response.Write(serializer.Serialize(kssForm.GetDocByUsername(username)));
                                context.Response.End();
                            }
                            break;
                        }
                    case "getdocbyApprover1":
                        context.Response.ContentType = "text/plain";
                        var usernameA1 = post["UserName"];
                        context.Response.Write(kssForm.GetDocByApprover1(usernameA1));
                        context.Response.End();
                        break;
                    case "getdocbyApprover2":
                        context.Response.ContentType = "text/plain";
                        var usernameA2 = post["UserName"];
                        context.Response.Write(kssForm.GetDocByApprover2(usernameA2));
                        context.Response.End();
                        break;
                    case "getdocbyTqm":
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(kssForm.GetDocByTqm());
                        context.Response.End();
                        break;
                    case "removeDoc":
                        string ID = post["id"];
                        if (!string.IsNullOrEmpty(ID))
                        {
                            ID = ID.Trim();
                            context.Response.Write(kssForm.DeleteDoc(ID));
                            context.Response.End();
                        }
                        context.Response.Write(serializer.Serialize(new Result(false, "Please check doc id")));
                        context.Response.End();
                        break;
                    case "saveImage":

                        var ext = System.IO.Path.GetExtension(context.Request.Files[0].FileName);
                        var fileName = Path.GetFileName(context.Request.Files[0].FileName);

                        if (context.Request.Files[0].FileName.LastIndexOf("\\") != -1)
                        {
                            fileName = context.Request.Files[0].FileName.Remove(0, context.Request.Files[0].FileName.LastIndexOf("\\")).ToLower();
                        }


                        uploadFolder = System.Web.Configuration.WebConfigurationManager.AppSettings["uploadFolder"] ?? "uploadFolder/";
                        fileName = KSSMaster.GetUniqueFileName(fileName, HttpContext.Current.Server.MapPath(uploadFolder + ADAuthen + "/"), ext).ToLower();



                        string location = HttpContext.Current.Server.MapPath(uploadFolder + ADAuthen + "/") + fileName + ext;
                        if (!Directory.Exists(Path.GetDirectoryName(location)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(location));
                        }
                        context.Request.Files[0].SaveAs(location);
                        var docSaveImage = new tblDoc();
                        int propsID = -1;
                        if (context.Request.QueryString["id"] == null)
                        {
                            docSaveImage.id = KSSMaster.createDocumentID();
                            docSaveImage.createdDate = DateTime.Now;

                            var prop = new docPropertyData
                            {
                                docId = docSaveImage.id,
                                propertyName = "docImage",
                                dataNvarchar =
                                    "/" + uploadFolder + ADAuthen + "/" + fileName + ext
                            };
                            var props = new List<docPropertyData> { prop };
                            kssForm.AddDoc(docSaveImage, props);
                        }
                        else
                        {
                            docSaveImage.id = context.Request.QueryString["id"];
                            var prop = new docPropertyData
                                                        {
                                                            docId = context.Request.QueryString["id"],
                                                            propertyName = "docImage",
                                                            dataNvarchar =
                                                                "/" + uploadFolder + ADAuthen + "/" + fileName + ext
                                                        };

                            var props = new List<docPropertyData> { prop };

                            kssForm.AddDocProperties(props, out props);
                            if (props.Count > 0 && props[0].id != null)
                            {
                                propsID = props[0].id;
                            }
                        }
                        //JsonConvert.SerializeObject(new Directory(){test: "test", test2: "test2"});

                        var result = new ImageUpload()
                                         {
                                             propid = propsID,
                                             imgPath = "/" + uploadFolder + ADAuthen + "/" + fileName + ext
                                         };
                        var resultRetrun = JsonConvert.SerializeObject(result);

                        context.Response.Headers.Add("Content-type", "text/json");
                        context.Response.Headers.Add("Content-type", "application/json");
                        context.Response.Write(resultRetrun);
                        context.Response.End();
                        break;
                    case "deleteImage":
                        var deleteDocId = context.Request.QueryString["id"];
                        var deletefile = context.Request.QueryString["file"];
                        var deletePropId = context.Request.QueryString["propid"];
                        var deleteprop = new docPropertyData
                                                        {
                                                            id = Convert.ToInt32(deletePropId),
                                                            docId = deleteDocId,
                                                            propertyName = "docImage",
                                                            dataNvarchar = deletefile
                                                        };
                        kssForm.DeleteProperties(deleteprop);
                        if (context.Request.QueryString.Count > 0)
                        {
                            uploadFolder = System.Web.Configuration.WebConfigurationManager.AppSettings["uploadFolder"] ?? "uploadFolder/";
                            string filePath = HttpContext.Current.Server.MapPath(deletefile);
                            if (File.Exists(filePath))
                                File.Delete(filePath);
                        }
                        break;

                    case "GetUserByRole":
                        var role = post["Role"];
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(UserHelper.GetAllUserExceptSelf(HttpContext.Current.User.Identity.Name));
                        context.Response.End();
                        break;
                    case "getchartbyMonth":
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(ChartHelper.GetDocGrpByMonth(DateTime.Today.Year));
                        context.Response.End();
                        break;
                    case "GetBarChartByYear":
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(ChartHelper.GetBarChartByYear());
                        context.Response.End();
                        break;
                    case "GetBarChartEveryYear":
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(ChartHelper.GetBarChartEveryYear());
                        context.Response.End();
                        break;

                    case "GetBarTargetYear":
                         context.Response.ContentType = "text/plain";
                        context.Response.Write(ChartHelper.GetBarTargetYear());
                        context.Response.End();
                        break;

                    case "GetBarTargetBySectionByYear":
                        var targetYear = post["year"];
                        int targetYearInt = DateTime.Today.Year;
                        if (!string.IsNullOrEmpty(targetYear))
                        {
                            Int32.TryParse(targetYear, out targetYearInt);
                        }
                        context.Response.ContentType = "text/plain";

                        context.Response.Write(ChartHelper.GetBarTargetBySectionByYear(targetYearInt));
                        context.Response.End();
                        break;
                        
                    case "GetPieChart":
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(ChartHelper.GetPieChart(DateTime.Today.Year));
                        context.Response.End();
                        break;


                    case "GetDocGrpByMonthByLocation":
                        var locationChart = post["locationChart"] ?? "NIT - Rayong";
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(ChartHelper.GetDocGrpByMonthByLocation(DateTime.Today.Year, locationChart));
                        context.Response.End();
                        break;

                    case "GetDocGrpA1":
                        context.Response.ContentType = "text/plain";
                        var chartTypeID = post["chartTypeID"] ?? "-1";
                        context.Response.Write(chartTypeID == "-1"
                                                   ? ChartHelper.GetDocGrpA1()
                                                   : ChartHelper.GetDocGrpA1(chartTypeID));
                        context.Response.End();
                        break;

                    case "GetDocGrpCateA1":
                        context.Response.ContentType = "text/plain";
                        var chartTypeID2 = post["chartTypeID"] ?? "-1";
                        context.Response.Write(chartTypeID2 == "-1"
                                                   ? ChartHelper.GetDocGrpByCateA1()
                                                   : ChartHelper.GetDocGrpByCateA1(chartTypeID2));
                        context.Response.End();
                        break;

                    case "GetDocGrpAlldata":
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(ChartHelper.GetDocGrpA1NoGroup());
                        context.Response.End();
                        break;
                    case "GetDocGrpByCash":
                        context.Response.ContentType = "text/plain";
                        var resultByCash = ChartHelper.GetDocGrpByCash();
                        context.Response.Write(resultByCash);
                        context.Response.End();
                        break;
                    case "getexpectDocs":
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(ChartHelper.GetExpectDoc());
                        context.Response.End();
                        break;
                    case "addexpectDoc":
                        context.Response.ContentType = "text/plain";
                        var expectNumberExpectDoc = post["expectNumber"] ?? "0";
                        var monthExpectDoc = post["month"] ?? DateTime.Today.Month.ToString();
                        var yearExpectDoc = post["year"] ?? DateTime.Today.Year.ToString();

                        var isEnableExpectDoc = post["isEnable"];
                        var addexpectDoc = new tblExpectDoc()
                        {
                            expectNumber = Convert.ToInt32(expectNumberExpectDoc),
                            datetime = new DateTime(Convert.ToInt32(yearExpectDoc), Convert.ToInt32(monthExpectDoc), 1),
                            isEnable = Convert.ToBoolean(isEnableExpectDoc)
                        };
                        context.Response.Write(ChartHelper.AddExpectDoc(addexpectDoc));
                        context.Response.End();
                        break;
                    case "editexpectDoc":
                        context.Response.ContentType = "text/plain";
                        var expectNumberid = post["id"];
                        var expectNumberExpectDoc2 = post["expectNumber"];
                        var monthExpectDoc2 = post["month"];
                        var yearExpectDoc2 = post["year"];

                        var isEnableExpectDoc2 = post["isEnable"];

                        int idexpectdoc = -1;
                        int.TryParse(expectNumberid, out idexpectdoc);
                        if (idexpectdoc == -1)
                        {
                            serializer.Serialize(new Result(false, "กรุณาตรวจสอบเลขที่"));
                            context.Response.End();
                        }
                        else
                        {
                            var editexpectDoc = new tblExpectDoc()
                                                    {
                                                        id = idexpectdoc,
                                                        expectNumber = Convert.ToInt32(expectNumberExpectDoc2),
                                                        datetime =
                                                            new DateTime(Convert.ToInt32(yearExpectDoc2),
                                                                         Convert.ToInt32(monthExpectDoc2), 1),
                                                        isEnable = Convert.ToBoolean(isEnableExpectDoc2)
                                                    };
                            var editexpectDocs = new List<tblExpectDoc> { editexpectDoc };
                            context.Response.Write(ChartHelper.EditExpectDoc(editexpectDocs));
                            context.Response.End();
                        }
                        break;

                    case "addHrUser":
                        context.Response.ContentType = "text/plain";
                        value = post["postData"];
                        List<tblEDMSHR> hrUser = JsonConvert.DeserializeObject<List<tblEDMSHR>>(value);
                        hrUser.ForEach(item => item.mtypeid = 1);
                        context.Response.Write(UserHelper.addHrUser(hrUser));
                        context.Response.End();
                        break;
                    case "updateHrUser":
                        context.Response.ContentType = "text/plain";
                        value = post["postData"];
                        List<tblEDMSHR> hrUserEdit = JsonConvert.DeserializeObject<List<tblEDMSHR>>(value);
                        context.Response.Write(UserHelper.updateHrUser(hrUserEdit));
                        context.Response.End();
                        break;

                    case "resetPassword":
                        context.Response.ContentType = "text/plain";
                        value = post["password"];
                        context.Response.Write(UserHelper.resetPassword(value.ToString()));
                        context.Response.End();
                        break;

                    case "removeExpectDoc":
                        context.Response.ContentType = "text/plain";
                        string expecDocID = post["id"];
                        if (!string.IsNullOrEmpty(expecDocID))
                        {
                            int iexpecDocID = -1;
                            int.TryParse(expecDocID, out iexpecDocID);
                            context.Response.Write(ChartHelper.DeleteExpectDoc(iexpecDocID));
                            context.Response.End();
                        }
                        context.Response.Write(serializer.Serialize(new Result(false, "กรุณาตรวจสอบเลขที่")));
                        context.Response.End();
                        break;

                    case "getNonEmp":
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(serializer.Serialize(UserHelper.getNonEmp()));
                        context.Response.End();
                        break;
                    case "deleteHrUser":
                        context.Response.ContentType = "text/plain";
                        var hrid = post["hrid"];
                        if (!string.IsNullOrEmpty(hrid))
                        {
                            context.Response.Write(UserHelper.deleteHrUser(hrid));
                            context.Response.End();
                        }
                        context.Response.Write(serializer.Serialize(new Result(false, "กรุณาตรวจสอบรหัสพนักงาน")));
                        context.Response.End();
                        break;

                    case "doSearch":
                        value = post["postData"];
                        var searchParam = JsonConvert.DeserializeObject<List<SearchCiteria>>(value);
                        if (searchParam.Count > 0)
                        {
                            List<tblDocSearch> ds = Search.GetSearchQuery(searchParam[0]);
                            //var test = ExportExcel.ExportByMonth(DateTime.Today.Month, "SB");
                            var exportCSVsearch = post["iscsv"];
                            if (!string.IsNullOrEmpty(exportCSVsearch) && exportCSVsearch == "true")
                            {
                                var ds2 = ds.Select(s => new { s.id, s.title, s.createdBy, s.createdByName, s.departmentName, dateCreate = s.createdDate.ToShortDateString(), s.CostSaving, s.cash });
                                using (ExcelPackage pck = new ExcelPackage())
                                {
                                    //Create the worksheet
                                    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Data");
                                    ws.Cells["A1"].LoadFromCollection(ds2, true);
                                    context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                                    context.Response.AddHeader("content-disposition", "attachment;  filename=dataExport.xlsx");
                                    context.Response.BinaryWrite(pck.GetAsByteArray());
                                    context.Response.End();
                                }
                            }
                            else
                            {
                                context.Response.ContentType = "text/plain";
                                context.Response.Write(serializer.Serialize(ds));
                            }
                        }
                        context.Response.End();
                        break;
                    case "doQuickSearch":
                        value = post["postData"];
                        if (!string.IsNullOrEmpty(value))
                        {
                            List<tblDocSearch> dsQuickSearch = Search.GetQuickSearchQuery(value);
                            context.Response.ContentType = "text/plain";
                            context.Response.Write(serializer.Serialize(dsQuickSearch));
                        }
                        break;
                    case "saveExcel":
                        value = post["postData"];
                        var exportParam = JsonConvert.DeserializeObject<List<SearchCiteria>>(value);
                        if (exportParam[0].Location.ToLower() == "bs")
                        {
                            List<ReportSB> sbReport1 = kssForm.GetReportSB(-1, exportParam[0]);

                            Utilities.Excel.CreateSBExcel(sbReport1, context.Server.MapPath("/excel/BS.xlsx"), context.Response);
                        }
                        else if (exportParam[1].DivName != null && exportParam[1].DivName.ToLower() == "technologyry")
                        {
                            List<ReportRYTechno> thReport = kssForm.GetReportRyTechnology(-1, exportParam[0]);
                            Utilities.Excel.CreateRYTHExcel(thReport, context.Server.MapPath("/excel/UpdateMPSheet_TC.xlsx"), context.Response);
                        }
                        else
                        {
                            List<ReportRy> ryReport = kssForm.GetReportRy(-1, exportParam[0]);
                            List<cashGroupSB> cashReport = null;
                            List<cashGroupSB> cashReportMonth = null;
                            ExportExcel.GetReportMoneyRateGroup(System.DateTime.Today.Month, exportParam[0], out cashReport, out cashReportMonth);
                            List<cateGroupSB> cateA1 = ExportExcel.GetReportAllCateGroup(System.DateTime.Today.Month, exportParam[0]);
                            List<cateGroupSB> cateUser = new List<cateGroupSB>();
                            cateUser.Add(new cateGroupSB { CateItem = "Pallet(Injection)", CateItemId = 1063, CateName = "ปรับปรุงเครื่องจักร" });
                            cateUser.Add(new cateGroupSB { CateItem = "Pallet(Injection)", CateItemId = 1064, CateName = "ปรับปรุงเครื่องจักร" });
                            cateUser.Add(new cateGroupSB { CateItem = "Profile(Extrusion)", CateItemId = 1065, CateName = "ปรับปรุงเครื่องจักร" });
                            cateUser.Add(new cateGroupSB { CateItem = "Pipe (Exrusion)", CateItemId = 1066, CateName = "ปรับปรุงเครื่องจักร" });
                            cateUser.Add(new cateGroupSB { CateItem = "WPC (Extrusion)", CateItemId = 1067, CateName = "ปรับปรุงเครื่องจักร" });
                            cateUser.Add(new cateGroupSB { CateItem = "Window & Door Fabrication", CateItemId = 1068, CateName = "ปรับปรุงเครื่องจักร" });
                            cateUser.Add(new cateGroupSB { CateItem = "อื่นๆ", CateItemId = 1069, CateName = "ปรับปรุงเครื่องจักร" });

                            cateUser.Add(new cateGroupSB { CateItem = "Fitting", CateItemId = 2000, CateName = "ปรับปรุงสินค้า" });
                            cateUser.Add(new cateGroupSB { CateItem = "Pallet", CateItemId = 2001, CateName = "ปรับปรุงสินค้า" });
                            cateUser.Add(new cateGroupSB { CateItem = "Profile", CateItemId = 2002, CateName = "ปรับปรุงสินค้า" });
                            cateUser.Add(new cateGroupSB { CateItem = "Pipe", CateItemId = 2003, CateName = "ปรับปรุงสินค้า" });
                            cateUser.Add(new cateGroupSB { CateItem = "WPC", CateItemId = 2004, CateName = "ปรับปรุงสินค้า" });
                            cateUser.Add(new cateGroupSB { CateItem = "Window & Door", CateItemId = 2005, CateName = "ปรับปรุงสินค้า" });
                            cateUser.Add(new cateGroupSB { CateItem = "อื่นๆ", CateItemId = 2006, CateName = "ปรับปรุงสินค้า" });


                            cateUser.Add(new cateGroupSB { CateItem = "ลดค่าใช้จ่าย", CateItemId = 3000, CateName = "ปรับปรุงวิธีการทำงาน" });
                            cateUser.Add(new cateGroupSB { CateItem = "สุขภาพและความปลอดภัย", CateItemId = 3001, CateName = "ปรับปรุงวิธีการทำงาน" });
                            cateUser.Add(new cateGroupSB { CateItem = "เพิ่มยอดขาย", CateItemId = 3002, CateName = "ปรับปรุงวิธีการทำงาน" });
                            cateUser.Add(new cateGroupSB { CateItem = "เพิ่มความพึงพอใจของลูกค้า", CateItemId = 3003, CateName = "ปรับปรุงวิธีการทำงาน" });
                            cateUser.Add(new cateGroupSB { CateItem = "WPC", CateItemId = 3004, CateName = "ปรับปรุงวิธีการทำงาน" });
                            cateUser.Add(new cateGroupSB { CateItem = "ลดเวลา / ขั้นตอนการงานที่ไม่จำเป็น", CateItemId = 3005, CateName = "ปรับปรุงวิธีการทำงาน" });
                            cateUser.Add(new cateGroupSB { CateItem = "อื่นๆ", CateItemId = 3006, CateName = "ปรับปรุงวิธีการทำงาน" });

                            cateUser = ExportExcel.GetReportAllCateUserGroup(System.DateTime.Today.Month, cateUser, exportParam[0]);
                            Utilities.Excel.modifyExcel(ryReport,
                                cashReport,
                                cashReportMonth,
                                cateA1,
                                cateUser,
                                context.Server.MapPath("/excel/ReportTQM.xlsx"), context.Response);
                        }
                        //context.Response.End();
                        break;
                    case "saveCashExcel":
                        value = post["postData"];
                        var exportCash = JsonConvert.DeserializeObject<List<tblDoc>>(value);
                        Excel.SaveCashExcel(exportCash, context.Server.MapPath("/excel/SaveCash.xlsx"),
                                            context.Response);
                        context.Response.End();
                        break;
                }

            }
        }

        private bool sendEmail(tblDoc doc)
        {
            string emailTitle = string.Empty;
            string emailBody = string.Empty;
            string docTitle = doc.title;
            string ownerName = doc.createdByName;
            string docId = doc.id;
            string emailTo = string.Empty;
            string sendMailError = "";
            switch (doc.status)
            {
                case 0:
                    emailTo = UserHelper.GetUserbyUserName(doc.approver1).Email;
                    emailTitle = WebConfigurationManager.AppSettings["newDocEmailTitel1"];
                    emailTitle = string.Format(emailTitle, docId);
                    emailBody = HttpContext.Current.Server.HtmlDecode(WebConfigurationManager.AppSettings["newDocEmailBody1"]);
                    emailBody = string.Format(emailBody, docId, ownerName, docTitle);
                    break;
                case 10:
                    emailTo = UserHelper.GetUserbyUserName(doc.approver2).Email;
                    emailTitle = WebConfigurationManager.AppSettings["newDocEmailTitel1"];
                    emailTitle = string.Format(emailTitle, docId);
                    emailBody = HttpContext.Current.Server.HtmlDecode(WebConfigurationManager.AppSettings["newDocEmailBody1"]);
                    emailBody = string.Format(emailBody, docId, ownerName, docTitle);
                    break;

                case 20:
                    emailTo = "redharing_555@hotmail.com";//UserHelper.getEmailTQMByLocation(doc.createdBy);
                    emailTitle = WebConfigurationManager.AppSettings["newDocEmailTitel2"];
                    emailTitle = string.Format(emailTitle, docId);
                    emailBody = HttpContext.Current.Server.HtmlDecode(WebConfigurationManager.AppSettings["newDocEmailBody2"]);
                    emailBody = string.Format(emailBody, docId, ownerName, docTitle);
                    break;

                case 30:
                    emailTo = UserHelper.GetUserbyUserName(doc.createdBy).Email;
                    emailTitle = WebConfigurationManager.AppSettings["newDocEmailTitelApprove"];
                    emailTitle = string.Format(emailTitle, docId);
                    emailBody = HttpContext.Current.Server.HtmlDecode(WebConfigurationManager.AppSettings["newDocEmailBodyApprove"]);
                    emailBody = string.Format(emailBody, ownerName, docId, docTitle);
                    break;

                case 11:
                    emailTo = UserHelper.GetUserbyUserName(doc.createdBy).Email;
                    emailTitle = WebConfigurationManager.AppSettings["newDocEmailTitelReject"];
                    emailTitle = string.Format(emailTitle, docId);
                    emailBody = HttpContext.Current.Server.HtmlDecode(WebConfigurationManager.AppSettings["newDocEmailBodyReject"]);
                    emailBody = string.Format(emailBody, ownerName, docId, docTitle);
                    break;

                default:
                    return false;
            }
            //emailTo = "redharing_555@hotmail.com";

            return Utilities.Email.SendMail(WebConfigurationManager.AppSettings["emailFrom"],
                                emailTo,
                             emailTitle,
                                emailBody,
                                out sendMailError);
        }

        public class ImageUpload
        {
            public int propid;
            public string docId;
            public string imgPath;
        }
        public class CheckItem
        {
            public string id;
            public string value;
        }
        public class AccountsView
        {
            public string UserName;
            public string UserID;
            public string Department;
            public List<CheckItem> test;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}